package com.csmy.my.center.util.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.csmy.my.center.module.MemeberInfo;
import com.csmy.my.center.util.CTConstants;
import com.csmy.my.center.util.CTUtils;
import com.csmy.my.center.util.RequestUtil;
import com.csmy.my.center.util.StringUtil;
import com.csmy.my.center.util.TokenProccessor;
import com.csmy.my.center.util.UniqueID;
import com.csmy.my.center.util.dataconvert.Dto;
import com.csmy.my.center.util.dataconvert.impl.BaseDto;
import com.csmy.my.center.util.db.JdbcTemplateTool;
import com.csmy.my.center.util.mail.MailUtil;
import com.csmy.my.center.util.sms.SMS_Sender;

public class SellPCClientServlet extends HttpServlet {

	private static final long serialVersionUID = 6072934341205662518L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
         //处理购买页面逻辑
		String reqPath = req.getRequestURI();
		String nowURl = req.getServletPath();
		String remote_ip = req.getRemoteAddr();
		String temp_path = nowURl.substring(nowURl.lastIndexOf("/") + 1, nowURl.length());
		StringUtil.xprint("reqPath:" + reqPath);
		StringUtil.xprint("temp路径:" + temp_path);
		StringUtil.xprint("正在访问URL:" +nowURl);
		StringUtil.xprint("当前路径:" + nowURl);
		
		Dto paramDto = RequestUtil.getPraramsAsDto(req);
		//处理购买
        if(reqPath.indexOf("spc")!=-1){
        	StringUtil.xprint("进入购买页面...");
        	String gparams[] = null;
        	String params [] = getParamFromURl(reqPath, temp_path);
        	if(CTUtils.isEmpty(params)||params.length!=3){
        		RequestUtil.renderHtml("<script>alert('对不起，您访问的页面不存在!');</script>");
        		return;
        	}
        	if(!params[1].equals("2")){
        		RequestUtil.renderHtml("<script>alert('对不起，URL参数错误!');</script>");
        		return;
        	}
        	
        	String copy_id = params[0];
        	String otp = params[1];
        	String pid = params[2];
        	if(CTUtils.isNotEmpty(pid)){
        		//处理空格
        		//new_pid = pid.replaceAll(" ", "\\+");
        		String gid = null;//商品ID
        		String uid = null;//用户ID(记录当前订单是由谁推广的)
        		String cid = null;//渠道ID
        		
        		gparams = CTUtils.decryptBased64(pid).split("-");
        		if(gparams.length>2){//包含渠道ID
        			gid = gparams[0];
        			uid = gparams[1];
        			cid = gparams[2];
        		}else {
        			gid = gparams[0];
        			uid = gparams[1];
				}
        		
        		MemeberInfo memeber = JdbcTemplateTool.getMemeberInfo(uid);
        		if(CTUtils.isNotEmpty(paramDto.getAsString("customer_tel"))){//提交订单成功
        			
        			//判断是否重复提交
        			boolean b = isRepeatSubmit(req);//判断用户是否是重复提交
                    if(b==true){
                        System.out.println("请不要重复提交....");
                        req.getRequestDispatcher("/wxb/payReSubResult.jsp").forward(req, resp);
                        return;
                    }
                    req.getSession().removeAttribute("token");//移除session中的token
                    System.out.println("处理用户提交请求....");
                    
        			//保存订单信息
        			String area = paramDto.getAsString("area");//地区
        			String province = paramDto.getAsString("province");//省份
        			String city = paramDto.getAsString("city");//市
        			String number = paramDto.getAsString("number");//数量
        			String addr = paramDto.getAsString("addr");//地址
        			String sku_id = paramDto.getAsString("sku_id");//套餐ID
        			String pay_type = paramDto.getAsString("pay_type");//支付方式
        			String customer_tel = paramDto.getAsString("customer_tel");//电话
        			String customer_name = paramDto.getAsString("customer_name");//名称
        			String customer_remark = paramDto.getAsString("customer_remark");//备注
        			
        			//处理客户提交的信息终端特殊字符 方式sql注入
        			addr = CTUtils.specialStrFilter(addr);
        			area = CTUtils.specialStrFilter(area);
        			city = CTUtils.specialStrFilter(city);
        			province = CTUtils.specialStrFilter(province);
        			customer_tel = CTUtils.specialStrFilter(customer_tel);
        			customer_name = CTUtils.specialStrFilter(customer_name);
        			customer_remark = CTUtils.specialStrFilter(customer_remark);
        			
        			//验证码
        			String captcha = paramDto.getAsString("captcha");
        			
        			Dto inDto = new BaseDto();
        			String order_id = UniqueID.getUniqueID(8, 0);
        			inDto.put("order_id", order_id);
        			inDto.put("order_time", CTUtils.getCurrentTime());
        			inDto.put("good_id", gid);
        			inDto.put("user_id", uid);
        			inDto.put("sku_id", sku_id);
        			inDto.put("channel_id", cid);
        			inDto.put("buy_num", number);
        			inDto.put("buyer_phone", customer_tel);
        			inDto.put("buyer_name", customer_name);
        			inDto.put("buyer_reamrk", customer_remark);
        			inDto.put("address", addr);
        			inDto.put("city", city);
        			inDto.put("area", area);
        			inDto.put("state", "1");//状态为1 已下单
        			inDto.put("pay_type", pay_type);
        			inDto.put("province", province);
        			inDto.put("order_ip", remote_ip);
        			//处理订单类型
        			String orderLog = "";
            		if(otp.equals("0")){
            			orderLog = "正常下单";
            			inDto.put("order_type", "0");//正常下单
            		}else if(otp.equals("1")){
            			orderLog = "代客下单";
            			inDto.put("order_type", "1");//代客下单
            		}else if(otp.equals("2")){
            			orderLog = "SPC下单";
            			inDto.put("order_type", "2");//SPC下单
            		}else{
            			orderLog = "异常订单";
            			inDto.put("order_type", "3");//异常订单
            		}
            		
            		//获取跳转地址
            		Dto good = JdbcTemplateTool.getGoodByID(gid);
            		//保存数据入库
            		if(JdbcTemplateTool.saveOrderInfo(inDto)){
	        			//记录订单日志
	        			JdbcTemplateTool.addOrderLog(order_id, "客户成功下单");
	        			//获取订单金额
	        			Dto skuInfo = JdbcTemplateTool.getGoodSkuByID(sku_id);
	        			double orderMonery = 0L;
	        			if(CTUtils.isNotEmpty(skuInfo)){
	        			    orderMonery = Double.valueOf(skuInfo.getAsString("sku_price"))*Integer.valueOf(number);
	        				req.setAttribute("orderMonery", orderMonery);
	        			}
	        			//处理IP
	        			if("0:0:0:0:0:0:0:1".equals(remote_ip)){
	        				remote_ip = "127.0.0.1";
	        			}
	        			//增加日志
	            		if(CTUtils.isNotEmpty(gid)){
	            			Dto logDto = new BaseDto();
	            			logDto.put("good_id", gid);
	            			logDto.put("user_id", uid);
	            			logDto.put("channel_id", cid);
	            			logDto.put("visit_num", "1");
	            			logDto.put("order_id", order_id);
	            			logDto.put("visit_ip", remote_ip);
	            			JdbcTemplateTool.addVisitBuyLog(logDto);
	            		}
	            		
	            		/*************************发送短信开始*************************/
                		String send_sms = CTUtils.getParamValue("SEND_ORDER_SMS");
                		String send_sms_temp = CTUtils.getParamValue("ORDER_SMS_TEMPLATE");
                		if(CTUtils.isNotEmpty(send_sms) && send_sms.equals("1") &&CTUtils.isNotEmpty(send_sms_temp)){
                			if(send_sms_temp.contains("buy_num")){
                				send_sms_temp = send_sms_temp.replaceAll("\\$buy_num", number);
                			}
                			if(send_sms_temp.contains("good_name")){
                				send_sms_temp = send_sms_temp.replaceAll("\\$good_name", good.getAsString("good_name"));
                			}
                			if(send_sms_temp.contains("order_money")){
                				send_sms_temp = send_sms_temp.replaceAll("\\$order_money", ""+orderMonery);
                			}
                			
                			String smString = send_sms_temp;
                			StringUtil.xprint("发送下单提示短信内容为>>>"+smString);
                			//String smString = "亲，您购买的"+number+"套商品【"+good.getAsString("good_name")+"】已经下单成功，订单总金额为："+orderMonery;
                			if(SMS_Sender.sendSms(customer_tel, smString)){
            					StringUtil.xprint("下单提示发送成功!");
            				}else{
            					StringUtil.xprint("下单提示短信发送失败!");
            				}
                		}
                		/*************************发短信件结束*************************/
	            		
                		/*************************发送邮件开始*************************/
	            		String send_mail = CTUtils.getParamValue("SEND_MAIL");
	            		if(CTUtils.isNotEmpty(send_mail) && send_mail.equals("1")){//需要发送邮件
	                		Dto mailDto = new BaseDto();
	                		//获取会员邮箱
	                		if(CTUtils.isNotEmpty(memeber)){
	                			if(CTUtils.isNotEmpty(memeber.getEmail())){
	                				mailDto.put("uemail", memeber.getEmail());
	                			}else{
	                				if(CTUtils.isNotEmpty(memeber.getQq_num())){
	                				   mailDto.put("uemail", memeber.getQq_num()+"@qq.com");
	                				}
	                			}
	                		}
	                		//获取商户的QQ号码
	                		String cqq_num = good.getAsString("QQ");
	                		if(CTUtils.isNotEmpty(cqq_num)){
	                			mailDto.put("cemail", cqq_num+"@qq.com");
	                		}
	                		
	                		mailDto.put("order_id", order_id);
	                		mailDto.put("order_time", CTUtils.getCurrentTime());
	                		mailDto.put("buy_name", customer_name);
	                		mailDto.put("address", addr);
	                		mailDto.put("ip", remote_ip);
	                		mailDto.put("money", req.getAttribute("orderMonery"));
	                		mailDto.put("log", orderLog);
	                		mailDto.put("buy_num", number);
	                		mailDto.put("user_acc", memeber.getAccount());
	                		mailDto.put("cust_name", good.getAsString("customer_name"));
	                		mailDto.put("good_name", good.getAsString("good_name"));
	                		mailDto.put("area", province+"-"+city+"-"+area);
	                		
	                		MailUtil.sendHtmlEmail(mailDto);
	                		
	                		/*************************发送邮件结束*************************/
	            		}
            		}
            		
            		
            		req.setAttribute("gdesc", good.getAsString("copy_desc"));
            		req.setAttribute("gourl", good.getAsString("forward_link"));
            		req.setAttribute("result_tips",  CTUtils.getParamValue("OEDER_RESULT_TIPS"));
        			req.getRequestDispatcher("/wxb/payResult.jsp").forward(req, resp);
            			
        			
        		}else{
	        		
	        		//获取商品信息
	        		Dto good = JdbcTemplateTool.getGoodByID(gid);
	        		req.setAttribute("goodInfo", good);
	        		//req.setAttribute("spqq", memeber.getQq_num());
	        		req.setAttribute("uid", uid);
	        		req.setAttribute("chid", cid);
	        		
	        		//获取套餐信息
	        		List<Dto> skuList = JdbcTemplateTool.getGoodSkuList(gid);
	        		req.setAttribute("skuList", skuList);
	        		//设置初始值
	        		if(!StringUtil.checkListBlank(skuList)){
	        		   Dto skuInfo = skuList.get(0);
	        		   req.setAttribute("sku_price", skuInfo.getAsString("sku_price"));
	        		}
	        		
	        		//获取商品文案信息
	        		Dto spcDto = JdbcTemplateTool.getSPCCopyInfo(copy_id);
	        		req.setAttribute("spcInfo", spcDto);
	        		
	        		//增加日志
            		if(CTUtils.isNotEmpty(gid)){
            			Dto logDto = new BaseDto();
            			logDto.put("good_id", gid);
            			logDto.put("user_id", uid);
            			logDto.put("channel_id", cid);
            			logDto.put("visit_num", "1");
            			logDto.put("visit_ip", remote_ip);
            			JdbcTemplateTool.addVisitBuyLog(logDto);
            		}
            		
            		CTUtils.getParamToReq(req);
            		//设置token令牌 防止重复提交
	        		String token = TokenProccessor.getInstance().makeToken();//创建令牌
	        		System.out.println("生成的token为:"+token);
	        		//在服务器使用session保存token(令牌)
	        		req.getSession().setAttribute("token", token);
	        		req.getRequestDispatcher("/wxb/newSpcBuyPage.jsp").forward(req, resp);
        		}
        	}
        }
	}
	
	
	/**
	 * 获取参数
	 * @param url
	 * @return
	 */
	public static String[] getParamFromURl(String url,String surl) {
		String params[]=null;
		if(StringUtil.isNotEmpty(url)){
			String tempUrl = url.substring(url.lastIndexOf(surl)+4, url.length());
			params = tempUrl.split("\\/");
		}
		for (int i = 0; i < params.length; i++) {
			StringUtil.xprint("params["+i+"]="+params[i]);
		}
		return params;
	}
	
	/**
     * 判断客户端提交上来的令牌和服务器端生成的令牌是否一致
     * @param request
     * @return 
     *         true 用户重复提交了表单 
     *         false 用户没有重复提交表单
     */
    private boolean isRepeatSubmit(HttpServletRequest request) {
        String client_token = request.getParameter("token");
        //1、如果用户提交的表单数据中没有token，则用户是重复提交了表单
        if(client_token==null){
            return true;
        }
        //取出存储在Session中的token
        String server_token = (String) request.getSession().getAttribute("token");
        //2、如果当前用户的Session中不存在Token(令牌)，则用户是重复提交了表单
        if(server_token==null){
            return true;
        }
        //3、存储在Session中的Token(令牌)与表单提交的Token(令牌)不同，则用户是重复提交了表单
        if(!client_token.equals(server_token)){
            return true;
        }
        
        return false;
    }

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}
